package com.handinfo.uimenu.window;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;

import com.handinfo.engine.AbstractGameScreen;
import com.handinfo.engine.GameMIDlet;
import com.handinfo.engine.GameManager;
import com.handinfo.engine.net.BaseConnection;
import com.handinfo.engine.net.GameProtocol;
import com.handinfo.game.UserScreen;
import com.handinfo.uimenu.UIListener;
import com.handinfo.uimenu.UIManager;
import com.handinfo.uimenu.UIPopmenu;
import com.handinfo.uimenu.UIWindowFactory;
import com.handinfo.util.Tools;


public class UIUserManager implements CommandListener
{
	public static UIUserManager m_instance;
	
	private Form form = new Form("登录");
	
	private Command ok = new Command("确定", Command.OK, 1);
	private Command back = new Command("返回", Command.BACK, 1);
	
	private static byte m_account_manage_select = 0;//账号管理索引
	public static final byte ACCOUNT_MANAGE_PASSWORD = 0;//账号管理 - 修改密码
	public static final byte ACCOUNT_MANAGE_BINDING = 1;//账号绑定
	public static final byte ACCOUNT_MANAGE_BACK = 2;//找回账号
	public static final byte ACCOUNT_MANAGE_UNBIND = 3;//解除绑定
	
	private TextField register_name = new TextField("", "", 20, TextField.ANY);
	private TextField register_phone = new TextField("", "", 20, TextField.PHONENUMBER);
	private TextField register_password1 = new TextField("", "", 20, TextField.PASSWORD);
	private TextField register_password2 = new TextField("", "", 20, TextField.PASSWORD);
	private TextField register_password3 = new TextField("", "", 20, TextField.PASSWORD);
	private TextField register_email = new TextField("", "", 50, TextField.EMAILADDR);
	public StringItem register_hint = new StringItem("", "", StringItem.PLAIN);
	
	private final byte ACCOUNT_MIN_SIZE = 6;//账号最小长度
	private final byte ACCOUNT_MAX_SIZE = 11;//账号最大长度
	
	private final byte PASSWORD_MIN_SIZE = 4;//密码最小长度
	private final byte PASSWORD_MAX_SIZE = 11;//密码最大长度
	
	public StringItem stringItem = new StringItem("", "", StringItem.PLAIN);
	
	/**
	 * 切换到修改密码
	 */
	private void changeToChangePassword() {		
		register_name.setLabel("当前账号 : ");
		register_name.setString(UserScreen.m_login_name == null ? "" : UserScreen.m_login_name);
		register_password1.setLabel("当前密码 : ");
		register_password1.setString(UserScreen.m_login_password == null ? "" : UserScreen.m_login_password);
		register_password2.setLabel("新密码 : ");
		register_password2.setString("");
		register_password3.setLabel("确认新密码 : ");
		register_password3.setString("");
		
		stringItem.setText("");
		stringItem.setLabel("");
		
		form.append(register_name);
		form.append(register_password1);
		form.append(register_password2);
		form.append(register_password3);
		form.append(stringItem);
		
		form.addCommand(ok);
		form.addCommand(back);
		form.setFormButtons();
		form.setCommandListener(this);
		Display.getDisplay(GameMIDlet.s_instance).setCurrent(form);
	}
	
	/**
	 * 切换到账号绑定
	 */
	private void changeToBinding() {
		form.deleteAll();
		
		register_name.setLabel("账号 : ");
		register_name.setString(UserScreen.m_login_name == null ? "" : UserScreen.m_login_name);
		register_password1.setLabel("密码 : ");
		register_password1.setString(UserScreen.m_login_password == null ? "" : UserScreen.m_login_password);
		register_phone.setLabel("绑定手机号 : ");
		register_phone.setString("");
		register_email.setLabel("绑定邮箱 : ");
		register_email.setString("");
		
		stringItem.setText("");
		stringItem.setLabel("");
		
		register_hint.setText("绑定手机号方便您找回自己的账号密码。请仔细确认输入手机号和邮箱的正确性。");
		
		form.append(register_name);
		form.append(register_password1);
		form.append(register_phone);
		form.append(register_email);
		form.append(stringItem);
		form.append(register_hint);
		form.addCommand(ok);
		form.addCommand(back);
		form.setFormButtons();
		form.setCommandListener(this);
		Display.getDisplay(GameMIDlet.s_instance).setCurrent(form);
	}
	
	/**
	 * 切换到密码找回
	 */
	private void changeToRetrievePassword() {
		form.deleteAll();
		
		register_phone.setLabel("已绑定的手机号 : ");
		register_phone.setString("");
		register_email.setLabel("已绑定的邮箱 : ");
		register_email.setString("");
		
		stringItem.setText("");
		stringItem.setLabel("");
		
		register_hint.setText("选择手机号或者邮箱一种输入。就可以收到账号密码信息。");
		
		form.append(register_phone);
		form.append(register_email);
		form.append(stringItem);
		form.append(register_hint);
		form.addCommand(ok);
		form.addCommand(back);
		form.setFormButtons();
		form.setCommandListener(this);
		Display.getDisplay(GameMIDlet.s_instance).setCurrent(form);
	}
	
	/**
	 * 切换到解除账号绑定
	 */
	private void changeToUnbind() {
		form.deleteAll();
		
		register_name.setLabel("账号 : ");
		register_name.setString(UserScreen.m_login_name == null ? "" : UserScreen.m_login_name);
		register_password1.setLabel("密码 : ");
		register_password1.setString(UserScreen.m_login_password == null ? "" : UserScreen.m_login_password);
		
		stringItem.setText("");
		stringItem.setLabel("");
		
		form.append(register_name);
		form.append(register_password1);
		form.append(stringItem);
		
		form.addCommand(ok);
		form.addCommand(back);
		form.setFormButtons();
		form.setCommandListener(this);
		Display.getDisplay(GameMIDlet.s_instance).setCurrent(form);
	}
	
	protected void dispose()
	{
		if(form != null){
			form.deleteAll();
			form = null;
		}
	}
	
	public static void recvNpcUser(byte type){
		switch(type){
			case ACCOUNT_MANAGE_PASSWORD:
				m_account_manage_select = ACCOUNT_MANAGE_PASSWORD;
				m_instance = null;
				m_instance = new UIUserManager();
				m_instance.changeToChangePassword();
				break;
			case ACCOUNT_MANAGE_BINDING:
				m_account_manage_select = ACCOUNT_MANAGE_BINDING;
				m_instance = null;
				m_instance = new UIUserManager();
				m_instance.changeToBinding();
				break;
			case ACCOUNT_MANAGE_BACK:
				m_account_manage_select = ACCOUNT_MANAGE_BACK;
				m_instance = null;
				m_instance = new UIUserManager();
				m_instance.changeToRetrievePassword();
				break;
			case ACCOUNT_MANAGE_UNBIND:
				m_account_manage_select = ACCOUNT_MANAGE_UNBIND;
				m_instance = null;
				m_instance = new UIUserManager();
				m_instance.changeToUnbind();
				break;
		}

	}
	
	
	private String checkAccount(String account) {
		if (account == null || account.equals("")) {
			return "账号不能为空!";
		} else if (account.length() < ACCOUNT_MIN_SIZE) {
			return "账号不能少于" + ACCOUNT_MIN_SIZE + "个字符!";
		} else if (account.length() > ACCOUNT_MAX_SIZE) {
			return "账号不能超过" + ACCOUNT_MAX_SIZE + "个字符!";
		} else if (isIncludeChinese(account)) {
			return "账号不能为中文";
		}
		return null;
	}
	
	private String checkPassword(String password) {
		if (password == null || password.equals("")) {
			return "密码不能为空!";
		} else if (password.length() < PASSWORD_MIN_SIZE) {
			return "密码不得少于" + PASSWORD_MIN_SIZE + "位!";
		} else if (password.length() > PASSWORD_MAX_SIZE) {
			return "密码不得高于" + PASSWORD_MAX_SIZE + "位!";
		} else if (isIncludeChinese(password)) {
			return "密码不能为中文!";
		}
		return null;
	}
	
	/**
	 * 检查字符串中是否有中文
	 * @param text
	 * @return
	 */
	private boolean isIncludeChinese(String text)
	{
		byte[] bytes = text.getBytes();
		for (int i = 0; i < bytes.length; i++) {
			if (bytes[i] == 63) {
				return true;
			}
		}
		return false;
	}
	
	public void commandAction(Command key, Displayable dis)
	{
		if (key == back) {
			if( m_instance != null){
				m_instance.dispose();
			}
			Display.getDisplay(GameMIDlet.s_instance).setCurrent(GameMIDlet.s_canvas);
		}else{
			switch (m_account_manage_select) {
				case ACCOUNT_MANAGE_PASSWORD:
					String new1 = register_password2.getString();
					String new2 = register_password3.getString();
					String old = register_password1.getString();
					String resultAccount = checkAccount(register_name.getString());
					String resultPassword = checkPassword(register_password1.getString());
					String reultNew1 = checkPassword(new1);
					String reultNew2 = checkPassword(new2);
					if (resultAccount != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(resultAccount);
					} else if (resultPassword != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(resultPassword);
					} else if (reultNew1 != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(reultNew1);
					} else if (reultNew2 != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(reultNew2);
					} else if (!new1.equals(new2)) {
						stringItem.setLabel("提示 :");
						stringItem.setText("两次新密码不符!");
					} else if (old.equals(new1)) {
						stringItem.setLabel("提示 :");
						stringItem.setText("旧密码与新密码相同!");
					} else {
						stringItem.setLabel("提示 :");
						stringItem.setText("服务请求中...");
						GameManager.getInstance().m_game_message.sendUserChangePassword(register_name.getString(), UserScreen.m_user_id, old, new1);
					}
					break;
				case ACCOUNT_MANAGE_BINDING:
					resultAccount = checkAccount(register_name.getString());
					resultPassword = checkPassword(register_password1.getString());
					String phone = register_phone.getString();
					String email = register_email.getString();
					if (resultAccount != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(resultAccount);
					} else if (resultPassword != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(resultPassword);
					}
					if( (phone == null || phone.equals("")) && (email == null || email.equals(""))){
						stringItem.setLabel("提示 :");
						stringItem.setText("手机号与邮箱需要填写一项!");
					}
					else if ( phone == null || phone.length() != 11) {
						if (email != null && !email.equals("")) {
							if (GameManager.getInstance().getConnection() == null) {
								try {
									GameManager.getInstance().m_game_message.unlockNetwork();
									GameManager.getInstance().createConnection(GameManager.SERVER_URL, GameManager.SERVER_PORT);
									GameManager.getInstance().getConnection().open();
								} catch (Exception ex) {
									Tools.debug(ex);
								}
							}
							stringItem.setLabel("提示 :");
							stringItem.setText("服务请求中...");
							GameManager.getInstance().m_game_message.sendUserBinding(
									register_name.getString(), register_password1.getString(), "", email);
						} else {
							stringItem.setLabel("提示 :");
							stringItem.setText("手机号码格式不正确!");
						}
					} else if (email == null || email.equals("")) {
						if (phone.length() == 11) {
							if (GameManager.getInstance().getConnection() == null) {
								try {
									GameManager.getInstance().m_game_message.unlockNetwork();
									GameManager.getInstance().createConnection(GameManager.SERVER_URL, GameManager.SERVER_PORT);
									GameManager.getInstance().getConnection().open();
								} catch (Exception ex) {
									Tools.debug(ex);
								}
							}
							stringItem.setLabel("提示 :");
							stringItem.setText("服务请求中...");
							GameManager.getInstance().m_game_message.sendUserBinding(
									register_name.getString(), register_password1.getString(), phone, "");
						} else {
							stringItem.setLabel("提示 :");
							stringItem.setText("邮箱不能为空!");
						}
					} else {
						if (GameManager.getInstance().getConnection() == null) {
							try {
								GameManager.getInstance().m_game_message.unlockNetwork();
								GameManager.getInstance().createConnection(GameManager.SERVER_URL, GameManager.SERVER_PORT);
								GameManager.getInstance().getConnection().open();
							} catch (Exception ex) {
								Tools.debug(ex);
							}
						}
						stringItem.setLabel("提示 :");
						stringItem.setText("服务请求中...");
						GameManager.getInstance().m_game_message.sendUserBinding(
								register_name.getString(), register_password1.getString(), phone, "");

					}
					break;
				case ACCOUNT_MANAGE_UNBIND:
					resultAccount = checkAccount(register_name.getString());
					resultPassword = checkPassword(register_password1.getString());
					if (resultAccount != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(resultAccount);
					} else if (resultPassword != null) {
						stringItem.setLabel("提示 :");
						stringItem.setText(resultPassword);
					} else {
						stringItem.setLabel("提示 :");
						stringItem.setText("服务请求中...");
						GameManager.getInstance().m_game_message.sendUserUnbind(register_name.getString(), register_password1.getString());
					}
					break;
				case ACCOUNT_MANAGE_BACK:
					phone = register_phone.getString();
					email = register_email.getString();
					if (phone == null || phone.equals("")) {//手机号为空
						if (email != null && !email.equals("")) {
							stringItem.setLabel("提示 :");
							stringItem.setText("服务请求中...");
							GameManager.getInstance().m_game_message.sendUserRetrievePassword(phone, email);
						} else {
							stringItem.setLabel("提示 :");
							stringItem.setText("手机号与邮箱需要填写一项!");
						}
					} else if (email == null || email.equals("")) {//邮箱为空
						if (phone != null && !phone.equals("")) {
							if (phone.length() != 11) {
								stringItem.setLabel("提示 :");
								stringItem.setText("手机号长度不正确!");
							} else {
								stringItem.setLabel("提示 :");
								stringItem.setText("服务请求中...");
								GameManager.getInstance().m_game_message.sendUserRetrievePassword(phone, email);
							}
						} else {
							stringItem.setLabel("提示 :");
							stringItem.setText("手机号与邮箱需要填写一项!");
						}
					}else {
						if (phone.length() != 11) {
							stringItem.setLabel("提示 :");
							stringItem.setText("手机号长度不正确!");
						} else {
							stringItem.setLabel("提示 :");
							stringItem.setText("服务请求中...");
							GameManager.getInstance().m_game_message.sendUserRetrievePassword(phone, email);
						}
					}
					break;
			}
		}
		
	}
	
	/**
	 * 接收修改密码
	 * @param dis
	 * @throws IOException
	 */
	private void recvChangePassword(DataInputStream dis) throws IOException {
		byte status = dis.readByte();
		if (status == 0) {
			stringItem.setLabel("提示 :");
			stringItem.setText("未知错误!");
		} else if (status == 1) {
			UserScreen.m_login_password = dis.readUTF();
			GameManager.manageUserRMSData(GameManager.RMS_INDEX_USER, GameManager.R_WRITE);
			Display.getDisplay(GameMIDlet.s_instance).setCurrent(GameMIDlet.s_canvas);
			if( m_instance != null ){
				m_instance.dispose();
			}
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "修改密码成功！");
		} else if (status == 2) {
			stringItem.setLabel("提示 :");
			stringItem.setText("账号错误!");
		} else if (status == 3) {
			stringItem.setLabel("提示 :");
			stringItem.setText("密码错误!");
		}
	}
	
    
	/**
	 * 接收绑定账号
	 * @param dis
	 * @throws IOException
	 */
	private void recvAccountBinding(DataInputStream dis) throws IOException {
		byte status = dis.readByte();
		if (status == 0) {
			stringItem.setLabel("提示 :");
			stringItem.setText("未知错误!");
		} else if (status == 1) { 
			Display.getDisplay(GameMIDlet.s_instance).setCurrent(GameMIDlet.s_canvas);
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "绑定成功!");
		} else if (status == 2) {
			stringItem.setLabel("提示 :");
			stringItem.setText("账号错误!");
		} else if (status == 3) {
			stringItem.setLabel("提示 :");
			stringItem.setText("密码错误!");
		} else if (status == 4) {
			stringItem.setLabel("提示 :");
			stringItem.setText("已经绑定过!");
		}
	}

	/**
	 * 接收找回密码
	 * @param dis
	 * @throws IOException
	 */
	private void recvRetrievePassword(DataInputStream dis) throws IOException {
		byte status = dis.readByte();
		if (status == 0) {
			stringItem.setLabel("提示 :");
			stringItem.setText("未知错误!");
		} else if (status == 1) {
			Display.getDisplay(GameMIDlet.s_instance).setCurrent(GameMIDlet.s_canvas);
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "找回账号成功!");
		} else if (status == 5) {
			stringItem.setLabel("提示 :");
			stringItem.setText("与绑定的手机号码不一致!");
		} else if (status == 6) {
			stringItem.setLabel("提示 :");
			stringItem.setText("与绑定的邮箱不一致!");
		}
	}
	
	/**
	 * 接收解除绑定
	 * @param dis
	 * @throws IOException
	 */
	private void recvAccountUnbind(DataInputStream dis) throws IOException {
		byte status = dis.readByte();
		if (status == 0) {
			stringItem.setLabel("提示 :");
			stringItem.setText("未知错误!");
		} else if (status == 1) { 
			Display.getDisplay(GameMIDlet.s_instance).setCurrent(GameMIDlet.s_canvas);
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "解绑成功!");
		} else if (status == 2) {
			stringItem.setLabel("提示 :");
			stringItem.setText("账号错误!");
		} else if (status == 3) {
			stringItem.setLabel("提示 :");
			stringItem.setText("密码错误!");
		} else if (status == 4) {
			stringItem.setLabel("提示 :");
			stringItem.setText("已经绑定过!");
		}
	}
	
	public  void recvMessage(int type, byte[] body)
	{
		int order = BaseConnection.s_perseOrderID;
		Tools.debugPrintln("接收到指令号 : " + order);
		GameManager.getInstance().m_game_message.unlockNetwork();
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(body);
			DataInputStream dis = new DataInputStream(bais);
			switch (order) {
				case GameProtocol.SC_USER_CHANGE_PASSWORD:
					recvChangePassword(dis);
					break;
				case GameProtocol.SC_USER_BINDING:
					recvAccountBinding(dis);
					break;
				case GameProtocol.SC_USER_RETRIEVE_PASSWORD:
					recvRetrievePassword(dis);
					break;
				case GameProtocol.SC_USER_UNBIND:
					recvAccountUnbind(dis);
					break;
			}
			dis.close();
			bais.close();
			dis = null;
			bais = null;
		}
		catch (Exception ex) {
			GameManager.getInstance().m_game_message.unlockNetwork();
			Tools.debugPrintln("NPC用户中心异常！！");
			Tools.debug(ex);
		}
	}
}
